package org.xx.armory.swing.builders;

import org.xx.armory.objectparser.ParsedObjectBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static org.apache.commons.lang3.StringUtils.left;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;

public class MenuModelBuilder
        extends ParsedObjectBuilder<MenuModel>
        implements ActionRefContainer {

    private String title;
    private String mnemonic;
    private List<Object> children;

    public MenuModelBuilder() {
        this.title = "";
        this.mnemonic = "";
        this.children = new ArrayList<>();
    }

    public MenuModelBuilder setTitle(
            String title
    ) {
        this.title = title;
        return this;
    }

    public MenuModelBuilder setMnemonic(String mnemonic) {
        this.mnemonic = mnemonic;
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void addActionRef(
            String actionName
    ) {
        this.children.add(actionName);
    }

    public void addSubMenu(
            MenuModel subMenu
    ) {
        this.children.add(subMenu);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public MenuModel build() {
        final String title = trimToEmpty(this.title);
        final String mnemonic_ = left(trimToEmpty(this.mnemonic), 1);
        final char mnemonic = !mnemonic_.isEmpty() ? mnemonic_.charAt(0) : '\0';
        return new MenuModel(getLineInfo(), title, mnemonic,
                             children.stream().filter(Objects::nonNull).collect(Collectors.toList()));
    }
}
